// ActionScript file
import components.friendSuggestedVideo;
import components.loadingWin;

import flash.net.NetConnection;
import flash.net.Responder;
import flash.net.URLRequest;
import flash.net.navigateToURL;
import flash.utils.Dictionary;

import mx.charts.AreaChart;
import mx.collections.ArrayCollection;
import mx.collections.ArrayList;

public var gateway:NetConnection = new NetConnection();

public var userNickName:String;
private var accessUrl:String;
public var desktopAppUrl:String;
public var homepageUrl:String;
public var helpUrl:String;

private var loadingPopUp:loadingWin;
private function sendDataAfterComplete():void{
	
	// Connect to the pyAMF gateway
	this.pyAMFserverUrl = "http://youtunes-tau2010.appspot.com/gateway"; //this.loaderInfo.parameters.serverUrl;
	this.accessUrl = "http://youtunes-tau2010.appspot.com/";  
	this.desktopAppUrl = "http://youtunes-tau2010.appspot.com/desktopApp/YouTunes1.1.air";//this.loaderInfo.parameters.desktopUrl;
	this.homepageUrl = "http://youtunes-tau2010.appspot.com/home.html";  
	this.helpUrl = "http://youtunes-tau2010.appspot.com/help.html";  
	this.gateway.connect(this.pyAMFserverUrl);
	
	loadingPopUp = PopUpManager.createPopUp(this,loadingWin,true) as loadingWin;
	PopUpManager.centerPopUp(loadingPopUp);
	
	// updating the user_logout component with the user nickname
	this.getNickname();
	
	// getting the playlist list from the server
	this.retrievePlaylistList();
	
	// getting the suggestions from friends
	this.getSuggestionAndUnreadNum();
	
}

private var isWaiting:Boolean = true;
private function finishedLoading():void
{
	if (this.isWaiting)
	{
		this.isWaiting = false;
		PopUpManager.removePopUp(loadingPopUp);
		this.checkIfShouldOpenNewUserWindow();
	}
}

private function closeWin(evt:Event):void
{
	PopUpManager.removePopUp(loadingPopUp);
}

// ---------------------------- retrievePlaylistList -----------------------------------

private var playlistArr:Array;
private var shouldUploadDefualtPlaylistSongs:Boolean = true;

public function retrievePlaylistList():void
{
	this.gateway.call("PlaylistUtils.retrievePlaylistList", this.retrievePlaylistListResponder);
}

private var retrievePlaylistListResponder:Responder = new Responder( retrievePlaylistOnResult, onFault );

// Result handler method 
private function retrievePlaylistOnResult(result:Array): void
{
	this.playlistArr = result;
		
	// sending the playlist list to the playlist_list component
	playlistListComp.populatePlayListResult(this.playlistArr);
	
	// sending the playlist list to the actions_list component
	actionsListComp.playlistArr = this.playlistArr;
	
	this.getDefaultPlaylistKey(shouldUploadDefualtPlaylistSongs);
	shouldUploadDefualtPlaylistSongs = false;
}

public function getPlaylistList():Array
{
	return this.playlistArr;
}

// --------------------------------- createNewPlaylist --------------------------------------

public function createNewPlaylist(playlistName:String):void
{
	//actionsListComp.debug.text = "createNewPlaylist";
	this.gateway.call("PlaylistUtils.createNewPlaylist", this.createtPlaylistResponder, playlistName);
}

private var createtPlaylistResponder:Responder = new Responder(createPlaylistOnResult, onFault);

// Result handler method 
private function createPlaylistOnResult(result:Boolean): void
{
	//actionsListComp.debug.text = "createAndDeleteOnResult";
	this.retrievePlaylistList();
}

// --------------------------------- deletePlaylist --------------------------------------

public function deletePlaylist(plKey:String):void
{
	// if the deleted playlist is the current playlist
	if (curr_plylist.getCurrentPlaylist() == plKey)
	{
		shouldUploadDefualtPlaylistSongs = true;
	}
	
	
	//actionsListComp.debug.text = "deletePlaylist + " + plKey;
	this.gateway.call("PlaylistUtils.deletePlaylist", this.deletePlaylistResponder, plKey);
}

private var deletePlaylistResponder:Responder = new Responder(deletePlaylistOnResult, onFault);

// Result handler method 
private function deletePlaylistOnResult(result:Boolean): void
{
	//actionsListComp.debug.text = "deletePlaylistOnResult";
	this.retrievePlaylistList();
}

// ------------------------------------- addSong ------------------------------------------

private var tempAddedSongPl:String = null;
private var tempAddedSongObj:Object = null;

public function addSong(plKey:String, song:Object):void
{
	//actionsListComp.debug.text = "addSong";
	
	this.tempAddedSongPl = plKey;
	this.tempAddedSongObj = song;
	
	this.gateway.call("SongUtils.addSong", this.addSongResponder, plKey, song);
}

private var addSongResponder:Responder = new Responder(addSongResult, onFault);

// Result handler method 
private function addSongResult(sonkKey:String): void
{
	//actionsListComp.debug.text = "addSongResult";
	
	// if the song was added to the all playlist while other playlist is the current playlist
	if (this.tempAddedSongPl != curr_plylist.getCurrentPlaylist() && this.tempAddedSongPl == this.defaultPlaylistkey)
	{
		this.tempAddedSongObj.keyString = sonkKey;
		this.addExistingSongToPlaylist(curr_plylist.getCurrentPlaylist(), this.tempAddedSongObj);
	} else {
		this.addSongToCurrPlaylist(this.tempAddedSongPl, this.tempAddedSongObj, sonkKey);
		this.tempAddedSongObj = null;
		this.tempAddedSongPl = null;
	}
	
	
}

// ---------------------------------- addSongToPlaylist ---------------------------------------

public function addExistingSongToPlaylist(plKey:String, songObj:Object):void
{
	this.tempAddedSongPl = plKey;
	this.tempAddedSongObj = songObj;
	
	//actionsListComp.debug.text = "addExistingSongToPlaylist";
	
	this.gateway.call("SongUtils.addSongToPlaylist", this.addSongResponder, plKey, songObj.keyString);
}

// ----------------------------------- addExistingSongById ------------------------------------

public function addExistingSongById(songObj:Object, plKey:String):void
{
	if (plKey == null)
	{
		plKey = this.defaultPlaylistkey;
	}
	this.tempAddedSongPl = plKey;
	this.tempAddedSongObj = songObj;
	
	this.gateway.call("FriendsSuggestionUtils.addExistingSong", this.addSongResponder,songObj.keyString, plKey);
}

// ------------------------------------- deleteSong ------------------------------------------

public function deleteSong(plKey:String, songKey:String):void
{
	//actionsListComp.debug.text = "deleteSongFromPlaylist " + songKey;
	this.tempAddedSongPl = plKey;
	
	this.gateway.call("SongUtils.deleteSong", this.deleteSongResponder, songKey, plKey);
}

private var deleteSongResponder:Responder = new Responder(deleteSongResult, onFault);

// Result handler method 
private function deleteSongResult(ret:int): void
{
	//actionsListComp.debug.text = "deleteSongResult";
	
	this.removeSongFromCurrPlaylist();
	
	this.tempAddedSongPl = null;
}

// ------------------------------------- retrievePlaylist --------------------------------------- 

private var wantedPlaylistKey:String;

public function retrievePlaylist(plKey:String):void
{
	//actionsListComp.debug.text = "retrievePlaylist " + plKey;
	this.wantedPlaylistKey = plKey;
	this.gateway.call("SongUtils.retrievePlaylist", this.retrievePlaylistResponder, plKey, this.isRunnicOnAir);
	
}

private var retrievePlaylistResponder:Responder = new Responder(retrievePlaylistResult, onFault);

// Result handler method 
private function retrievePlaylistResult(songsArr:Array): void
{
	var songsArrColl:ArrayCollection = new ArrayCollection(songsArr);
	this.showPlaylist(this.wantedPlaylistKey, songsArrColl);
	this.wantedPlaylistKey = null;
	
	this.finishedLoading();
}

// ------------------------------------- edit song info ---------------------------------------

private function editSongInfo(songObj:Object):void
{
	//actionsListComp.debug.text = "editSongInfo";
	
	this.gateway.call("SongUtils.editSongInfo", this.editSongResponder, songObj);
}

private var editSongResponder:Responder = new Responder(editSongResult, onFault);

// Result handler method 
private function editSongResult(int:Number): void
{
	//actionsListComp.debug.text = "editSongResult";
}

// -------------------------------------- change song position --------------------------------

/*public function changeSongPos(plKey:String, songKey:String, oldIndex:int, newIndex:int):void
{
	actionsListComp.debug.text = "changeSongPos old:" + oldIndex + " new:" + newIndex;
	this.gateway.call("SongUtils.changeSongPosition", this.changeSongPosResponder, plKey, songKey, oldIndex, newIndex);
}
private var changeSongPosResponder:Responder = new Responder(changeSongPosResult, onFault);
private function changeSongPosResult(int:Number):void
{
	actionsListComp.debug.text = "changeSongPosResult";
}*/
// ---------------------------------- get song info from server -------------------------------

public function getMoreSongInfo(videoId:String):void
{
	//actionsListComp.debug.text = "getMoreSongInfo";
	this.gateway.call("SongUtils.fetchAvailableSongInfo", this.getMoreSongInfoResponder, videoId);
}
private var getMoreSongInfoResponder:Responder = new Responder(getMoreSongInfoResult, onFault);

// Result handler method 
private function getMoreSongInfoResult(infoObj:Object): void
{
	curr_plylist.openEditInfoPopUp(infoObj);
	//actionsListComp.debug.text = "getMoreSongInfoResult";
}
// ------------------------------------- update video ID ---------------------------------------

public function updateVideoID(songId:String, newVideoId:String):void
{
	this.gateway.call("SongUtils.updateSongVideoId", this.editSongResponder, songId, newVideoId);
}

// ------------------------------------- import playlist ---------------------------------------

public function importYoutubePlaylist(plName:String, songsArr:Array):void
{
	//actionsListComp.debug.text = "importYoutubePlaylist";
	this.gateway.call("PlaylistUtils.importPlaylist", this.importPlaylistResponder, plName, songsArr);
}

private var importPlaylistResponder:Responder = new Responder(importPlaylistResult, onFault);

// Result handler method 
private function importPlaylistResult(int:Number): void
{
	//actionsListComp.debug.text = "importPlaylistResult";
	this.retrievePlaylistList();
}

// ------------------------------------- rename playlist ---------------------------------------

public function renamePlaylist(plKey:String, newName:String):void
{
	//actionsListComp.debug.text = "renamePlaylist";
	this.gateway.call("PlaylistUtils.renamePlaylist", this.renamePlaylistResponder, plKey, newName);
}

private var renamePlaylistResponder:Responder = new Responder(renamePlaylistResult, onFault);

// Result handler method 
private function renamePlaylistResult(int:Number): void
{
	//actionsListComp.debug.text = "renamePlaylistResult";
	this.retrievePlaylistList();
}

// ----------------------------------------- logout -------------------------------------------

private var logoutResponder:Responder = new Responder(logoutResult, onFault);

// Result handler method 
private function logoutResult(logoutUrl:String): void
{
	//actionsListComp.debug.text = "logoutResult";
	navigateToURL(new URLRequest(logoutUrl), "_self");
}

// ------------------------------------ share song ---------------------------------------

public function sendSongSuggestion(emailArr:Array, videoId:String, songId:String):void
{
	//actionsListComp.debug.text = "sendSongSuggestion";
	this.gateway.call("FriendsSuggestionUtils.sendEmailToUsers", this.shareSongResponder, emailArr, videoId, songId);
}

private var shareSongResponder:Responder = new Responder(shareResult, onFault);

// Result handler method 
private function shareResult(int:Number): void
{
	//actionsListComp.debug.text = "shareResult";
}

// ---------------------------------- friends suggestions count -------------------------------
private var suggestionsNumResponder:Responder = new Responder(suggestionsNumResult, onFault);
public function getSuggestionAndUnreadNum():void
{
	//actionsListComp.debug.text = "getSuggestionAndUnreadNum";
	this.gateway.call("FriendsSuggestionUtils.getSuggestionAndUnreadNum", this.suggestionsNumResponder);
}

// Result handler method 
private function suggestionsNumResult(nums:Number): void
{
	//actionsListComp.debug.text = "suggestionsNumResult " + nums;
	searchAndSuggestionsTabs.setFriendsSuggestionsNumber(nums, nums);
}

// ------------------------------- friends suggestions video results --------------------------

public function getFriendsSuggestion(startIndex:int, resultNum:int):void
{
	//actionsListComp.debug.text = "startIndex:" + startIndex + " resultNum: " + resultNum;
	this.gateway.call("FriendsSuggestionUtils.getFriendsSuggestions", this.friendsSuggestionsResponder, startIndex, resultNum);
}

private var friendsSuggestionsResponder:Responder = new Responder(friendsSuggestionsResult, onFault);

// Result handler method 
private function friendsSuggestionsResult(friendsSuggestionsArr:Array): void
{
	//actionsListComp.debug.text = "friendsSuggestionsResult " + friendsSuggestionsArr[0].id;
	searchAndSuggestionsTabs.friendsSuggestionsContent.handleVideoDataResult(friendsSuggestionsArr);
}

// --------------------------------------- delete friend suggestion ---------------------------
private var suggestionObj:friendSuggestedVideo = null;
public function deleteFriendSuggestion(suggestionId:String, suggestionObj:friendSuggestedVideo):void
{
	//actionsListComp.debug.text = "deleteFriendSuggestion";
	this.suggestionObj = suggestionObj;
	this.gateway.call("FriendsSuggestionUtils.deleteSuggestion", this.delteFriendsSuggestionsResponder, suggestionId);
}

private var delteFriendsSuggestionsResponder:Responder = new Responder(deleteFriendsSuggestionResult, onFault);

// Result handler method 
private function deleteFriendsSuggestionResult(int:Number): void
{
	//actionsListComp.debug.text = "deleteFriendsSuggestionResult";
	searchAndSuggestionsTabs.friendsSuggestionsContent.deleteSuggestionByIndex(this.suggestionObj);
	this.suggestionObj = null;
}

// ---------------------------------- user nick name ------------------------------------------

public function getNickname():void
{
	//actionsListComp.debug.text = "getNickname";
	this.gateway.call("LogService.getNickname", this.nicknameResponder);
}

private var nicknameResponder:Responder = new Responder(nicknameResult, onFault);

// Result handler method 
//private function nicknameResult(nickname:String): void
private var isknownUser:Boolean = false;
private function nicknameResult(userObj:Object): void
{
	this.isknownUser = userObj.isKnown;
	user_logout.getInfo(userObj.nickname);
	//actionsListComp.debug.text = "nicknameResult " + userObj.isKnown;
}

// -------------------------------- add song from local computer ------------------------------

private var songsQueue:Dictionary = new Dictionary();
private var requestCounter:int = 0

public function saveLocalSong(plKey:String, song:Object):void
{
	var requestId:int = requestCounter++;
	songsQueue[requestId] = {addedSongPl:plKey, addedSongObj:song};
	
	this.gateway.call("SongUtils.addSongObjectByPath", this.saveLocalSongResponder, plKey, song, requestId);
	
	if(plKey!=this.defaultPlaylistkey){
		this.gateway.call("SongUtils.addSongObjectByPath", this.saveLocalSongResponder, this.defaultPlaylistkey, song, requestId);
	}
}

private var saveLocalSongResponder:Responder = new Responder(saveLocalSongResult, onFault);
private var searchAlternativeResponder:Responder = new Responder(searchAlternativeResult, onFault);

private function saveLocalSongResult(response:Object):void
{
	if(response!=null && response.plKey == curr_plylist.getCurrentPlaylist()){
		var obj:Object = songsQueue[response.requestId];
		if(obj!=null){
			obj.addedSongObj.keyString = response.songKey;
			var localSongIndex:Number = this.addSongToCurrPlaylist(obj.addedSongPl,obj.addedSongObj, response.songKey);
			obj.localSongIndex = localSongIndex;
			searchAlternative(response.songKey,response.requestId);
		}
	}
}

private function searchAlternative(songKey:String, requestId:int):void
{
//	this.localSongIndex = localSongIndex;
	this.gateway.call("SongUtils.searchForYoutubeRequestedSong", this.searchAlternativeResponder, songKey, requestId);
}

private function searchAlternativeResult(response:Object):void
{
	trace("Got response");
	if(response!=null){
		var obj:Object = songsQueue[response.requestId];
		if(obj!=null){
			trace("id: "+obj.addedSongObj.id+" videoId: "+response.videoId);
			obj.addedSongObj.id = response.videoId;
			if (obj.localSongIndex != -1)
			{
				curr_plylist.changeSongObj(obj.localSongIndex, obj.addedSongObj);
			}
			songsQueue[response.requestId] = null;
			delete songsQueue[response.requestId];
		}
	}
}

// --------------------------------------- user properties -----------------------------------

public function getProperties():void
{
	//actionsListComp.debug.text = "getProperties";
	this.gateway.call("PropertiesUtils.getProperties", this.getPropertiesResponder);
}

private var getPropertiesResponder:Responder = new Responder(getPropertiesResult, onFault);

// Result handler method 
private function getPropertiesResult(propObj:Object): void
{
	this.openPropertiesWindow(propObj);
	//actionsListComp.debug.text = "getPropertiesResult";
}

public function setProperties(propObj:Object):void
{
	//actionsListComp.debug.text = "setProperties";
	this.gateway.call("PropertiesUtils.setProperties", this.setPropertiesResponder, propObj);
}

private var setPropertiesResponder:Responder = new Responder(setPropertiesResult, onFault);

// Result handler method 
private function setPropertiesResult(int:Number): void
{
	//actionsListComp.debug.text = "setPropertiesResult";
}
// ---------------------------------- retrieve playlists from youtube ------------------------

public function getYouTubePlaylistsNames():void
{
	//actionsListComp.debug.text = "getYouTubePlaylistsNames";
	this.gateway.call("YoutubeUtils.retrievePlaylistsNames", this.nicknameResponder);
}

private var youtubePlaylistNameResponder:Responder = new Responder(youtubePlaylistNameResult, onFault);

// Result handler method 
private function youtubePlaylistNameResult(namesArr:Array): void
{
	//actionsListComp.debug.text = "name: " + namesArr[0].playlistName;
	//user_logout.getInfo(nickname);
}

// --------------------------------------------------------------------------------------------

// Fault handler method displays error message 
private function onFault( error:* ): void
{
	actionsListComp.debug.text = "";
	for (var i:Object in error){
		actionsListComp.debug.text += error[i] + " ; ";
	}
}
